#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Node
{
    int idx, key, next;
    bool flag;
} nodes[100000];
bool cmp(Node &n1, Node &n2)
{
    return !n1.flag || !n2.flag ? n1.flag > n2.flag : n1.key < n2.key;
}
int main()
{
    int n, cnt = 0, s, a, b, c;
    scanf("%d%d", &n, &s);
    for (int i = 0; i < n; i++)
    {
        scanf("%d%d%d", &a, &b, &c);
        nodes[a] = {a, b, c, false};
    }
    for (int i = s; i != -1; i = nodes[i].next)
    {
        nodes[i].flag = true;
        cnt++;
    }
    if (cnt == 0)
    {
        printf("0 -1");
    }
    else
    {
        sort(nodes, nodes + 100000, cmp);
        printf("%d %05d\n", cnt, nodes[0].idx);
        for (int i = 0; i < cnt - 1; i++)
            printf("%05d %d %05d\n", nodes[i].idx, nodes[i].key, nodes[i+1].idx);
        printf("%05d %d -1\n", nodes[cnt-1].idx, nodes[cnt-1].key);
    }
    return 0;
}